package com.ruoyi.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.RechargeItem;
import com.ruoyi.business.ao.RechargeAO;
import com.ruoyi.business.bo.RechargeBO;
import com.ruoyi.business.mapper.RechargeItemMapper;
import com.ruoyi.business.service.RechargeService;
import com.ruoyi.business.vo.RechargeListVO;
import com.ruoyi.common.common.ResultBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @title: RechargeController
 * @copyright: copyright (c) 2023
 * @author: jiangguanjun
 * @date: 2023/2/10 16:08
 * @firstReview:
 * @lastReview:
 * @desc:
 */
@Api(value = "RechargeController", tags = "充值相关")
@RestController
@Slf4j
@RequestMapping("/recharge")
public class RechargeController{

    @Autowired
    private RechargeService rechargeService ;

    @Autowired
    private RechargeItemMapper rechargeItemMapper ;

    @CrossOrigin
    @ApiOperation(value = "用户充值")
    @PostMapping("/recharge")
    public ResultBody recharge(@RequestBody RechargeAO rechargeAO){

        log.info("rechargeAO:::::::{}",rechargeAO);
        Long userId = SecurityUtils.getUserId() ;
        RechargeBO rechargeBO = new RechargeBO() ;
        rechargeBO.setuId(userId);
        rechargeBO.setRechargeItemId(rechargeAO.getRechargItemId());
        return rechargeService.recharge(rechargeBO) ;
    }

   /* @CrossOrigin
    @ApiOperation(value = "充值的退款")
    @PostMapping("/refund")
    public ResultBody<RefundResult> refund(@RequestBody RefundAO refundAO){

        return rechargeService.refund(refundAO) ;
    }*/

    @CrossOrigin
    @PostMapping("/notify")
    @ApiOperation(value = "充值回调")
    public JSONObject rechargeNotify(HttpServletRequest requestt) throws Exception {
        try {
            return rechargeService.rechargeNotify(requestt) ;
        }catch (Exception e){
            JSONObject jsonObject = new JSONObject() ;
            log.info("更新失败",e);
            jsonObject.put("code","FAIL") ;
            jsonObject.put("message","支付失败") ;
            return jsonObject ;
        }
    }

    @CrossOrigin
    @PostMapping("/refundNotify")
    @ApiOperation(value = "充值退款回调")
    public JSONObject refundNotify(HttpServletRequest requestt) throws Exception {
        try {
            return rechargeService.refundNotify(requestt) ;
        }catch (Exception e){
            JSONObject jsonObject = new JSONObject() ;
            log.info("退款失败",e);
            jsonObject.put("code","FAIL") ;
            jsonObject.put("message","支付失败") ;
            return jsonObject ;
        }
    }

    @CrossOrigin
    @ApiOperation(value = "充值列表，充值统计  页面：采购-充值记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createStartTime", value = "查询开始时间戳", dataType = "Long"),
            @ApiImplicitParam(name = "createEndTime", value = "查询结束时间戳", dataType = "Long"),
            @ApiImplicitParam(name = "uId", value = "用户id", dataType = "Integer")
    })
    @GetMapping("/list")
    public ResultBody<IPage<RechargeListVO>> list(@RequestParam (value = "createStartTime",required = false) String createStartTime,
                                                  @RequestParam(value="createEndTime",required = false) String createEndTime,
                                                  @RequestParam(value = "uId",required = false) Integer uId,
                                                  @RequestParam(value = "nike",required = false) String nike){


        log.info("createStartTime:::::{},createEndTime:::::::{}",createStartTime,createEndTime);
        if(StringUtils.isNotBlank(createStartTime) ){
            createStartTime += " 00:00:00" ;

        }

        if(StringUtils.isNotBlank(createEndTime)){
            createEndTime += " 23:59:59" ;
        }


        return rechargeService.listPage(createStartTime,createEndTime,uId,nike) ;
    }

    @CrossOrigin
    @ApiOperation(value = "充值列表导出")
    @GetMapping("/download")
    public void download(HttpServletResponse response,
                         @RequestParam (value = "createStartTime",required = false) String createStartTime,
                         @RequestParam(value="createEndTime",required = false) String createEndTime,
                         @RequestParam(value = "uId",required = false) Integer uId,
                         @RequestParam(value = "nike",required = false) String nike) throws IOException {
        List<RechargeListVO> rechargeListVOs = rechargeService.list(createStartTime,createEndTime,uId,nike) ;
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("充值记录"+System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), RechargeListVO.class).sheet("充值记录").doWrite(rechargeListVOs);
    }


    @CrossOrigin
    @ApiOperation(value = "获取当前用户充值项列表")
    @PostMapping("/rechargeItemList")
    public ResultBody<List<RechargeItem>> rechargeItemList() throws IOException {
        Long userId = SecurityUtils.getUserId() ;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        String dateTimeStr = format.format(new Date(System.currentTimeMillis())) ;
        List<RechargeItem> rechargeListVOs = rechargeItemMapper.getByUser(userId,dateTimeStr) ;

        return ResultBody.success(rechargeListVOs) ;
    }



}
